<?php

namespace app\api\controller;

use app\admin\model\Sendwxmsg;

use think\Controller;
use think\Db;
use think\Session;

class Shop extends Controller
{
    public $pagesize = 10;

    /**
     * 获取商品列表接口
     */
    public function lists()
    {
        $auth = trim(input("request.auth"));//用户auth
        $cls_id = trim(input("request.cls_id"));//用户auth
        $hot = trim(input("request.hot"));//用户auth
//        $userInfo = checkLoginExp($auth);
//        if (empty($userInfo)) {
//            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
//            return json($return);
//        }
        if (empty($cls_id)) {
            $return = ['err' => 1, 'msg' => '产品分类ID不正确'];
            return json($return);
        }


        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        $w = array();
        $w['is_delete'] = 0;//未删除
        $w['stats'] = 0;//已上架
        $w['cls_id'] = $cls_id;//已上架

        if (!empty($hot)) {
            $w['hot'] = 1;//已上架
        }


        $model = new \app\admin\model\Shop();
        $lists = $model->lists($w, $this->pagesize, "*", "sorts desc,id desc");
        $lists = $lists['data'];
        $lists = formateTimeForArr($lists, 'ctime');//获取发帖人信息
        $lists = changeUidToUserinfoForLists($lists, 'uid');//获取发帖人信息
        foreach ($lists as $key => $val) {
            $lists[$key]['shop_size'] = [];
            $lists[$key]['shop_color'] = [];
            if ($val['shop_size']) {
                $lists[$key]['shop_size'] = explode("||", $val['shop_size']);
            }
            if ($val['shop_color']) {
                $lists[$key]['shop_color'] = explode("||", $val['shop_color']);
            }


            $tmpGoodAttribute = getGoodAttr($val['id']);
            $goodAttribute = array();
            if ($tmpGoodAttribute['attr']) {
                $goodAttribute = json_decode($tmpGoodAttribute['attr'], true);
            }
            $lists[$key]['goodAttribute'] = $goodAttribute;
        }

        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $lists;
        return json($return);
    }
    public $preurl="https://manager.scajxd.com";

    /**
     * 获取一个商品详情接口
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info()
    {
//        $auth = trim(input("request.auth"));//用户auth
        $tid = trim(input("request.tid"));//商品ID
//        $userInfo = checkLoginExp($auth);
//        if (empty($userInfo)) {
//            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
//            return json($return);
//        }

        if (empty($tid)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tid]'];
            return json($return);
        }

        $model = new \app\admin\model\Shop();
        $info = $model->getID($tid);
        if (empty($info)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tid]'];
            return json($return);
        }

        if ($info['stats']) {
            $return = ['err' => 1, 'msg' => '获取失败,商品已经下架', 'devMsg' => '获取失败，帖子已经下架'];
            return json($return);
        }

        if ($info['is_delete']) {
            $return = ['err' => 1, 'msg' => '获取失败,上已经不存在', 'devMsg' => '获取失败，帖子已经不存在'];
            return json($return);
        }
        $info['ctime'] = formateDate($info['ctime']);
        $info['UserInfo'] = getUserInfoForID($info['uid']);//获取发帖人信息

        //增加浏览数
        incShopReadNum($tid);


        if ($info['shop_size']) {
            $info['shop_size'] = explode("||", $info['shop_size']);
        } else {
            $info['shop_size'] = [];
        }

        if ($info['shop_color']) {
            $info['shop_color'] = explode("||", $info['shop_color']);
        } else {
            $info['shop_color'] = [];
        }


        $tmpGoodAttribute = getGoodAttr($info['id']);
        $goodAttribute = array();
        if ($tmpGoodAttribute['attr']) {
            $goodAttribute = json_decode($tmpGoodAttribute['attr'], true);
        }
        $info['goodAttribute'] = $goodAttribute;
        $info['content']=dealContentsForImages( $info['content'],$this->preurl);

        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $info;
        return json($return);
    }


    public function info_web()
    {
//        $auth = trim(input("request.auth"));//用户auth
        $tid = trim(input("request.tid"));//商品ID
//        $userInfo = checkLoginExp($auth);
//        if (empty($userInfo)) {
//            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
//            return json($return);
//        }

        if (empty($tid)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tid]'];
            $this->assign('data', $return);
            return $this->fetch('edit');
        }

        $model = new \app\admin\model\Shop();
        $info = $model->getID($tid);
        if (empty($info)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tid]'];
            $this->assign('data', $return);
            return $this->fetch('edit');
        }

        if ($info['stats']) {
            $return = ['err' => 1, 'msg' => '获取失败,商品已经下架', 'devMsg' => '获取失败，帖子已经下架'];
            $this->assign('data', $return);
            return $this->fetch('edit');
        }

        if ($info['is_delete']) {
            $return = ['err' => 1, 'msg' => '获取失败,上已经不存在', 'devMsg' => '获取失败，帖子已经不存在'];
            $this->assign('data', $return);
            return $this->fetch('edit');
        }
        $info['ctime'] = formateDate($info['ctime']);
        $info['UserInfo'] = getUserInfoForID($info['uid']);//获取发帖人信息

        //增加浏览数
        incShopReadNum($tid);


        if ($info['shop_size']) {
            $info['shop_size'] = explode("||", $info['shop_size']);
        } else {
            $info['shop_size'] = [];
        }

        if ($info['shop_color']) {
            $info['shop_color'] = explode("||", $info['shop_color']);
        } else {
            $info['shop_color'] = [];
        }


        $tmpGoodAttribute = getGoodAttr($info['id']);
        $goodAttribute = array();
        if ($tmpGoodAttribute['attr']) {
            $goodAttribute = json_decode($tmpGoodAttribute['attr'], true);
        }
        $info['goodAttribute'] = $goodAttribute;


        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $info;
        $this->assign('data', $return);
        return $this->fetch('edit');
    }


    /**
     * 获取帖子回复列表接口
     */
    public function replyLists()
    {
        $auth = trim(input("request.auth"));//用户auth
        $tid = trim(input("request.tid"));//帖子ID
        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }

        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        if (empty($tid)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tid]'];
            return json($return);
        }


        $w = array();
        $w['is_delete'] = 0;//未删除
        $w['tid'] = $tid;
        $w['type'] = 0;//0回复 1点赞

        $model = new \app\admin\model\NotesReply();
        $lists = $model->lists($w, $this->pagesize);
        $lists = $lists['data'];
        $lists = formateTimeForArr($lists, 'ctime');//获取发帖人信息
        $lists = changeUidToUserinfoForLists($lists, 'uid', 'touid');//获取发帖人信息
        $lists = getNotesFilesForLists($lists, 1, "sorts desc,id desc");//批量获取帖子列表中的附件数据

        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $lists;
        return json($return);
    }


    /**
     * 批量获取帖子回复列表接口
     */
    public function replyPlLists()
    {
        $auth = trim(input("request.auth"));//用户auth
        $tids = trim(input("request.tids"));//帖子ID
        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }

        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        if (empty($tids)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tids]'];
            return json($return);
        }

        $tempTidsArray = explode(",", $tids);
        if (empty($tempTidsArray)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tids]'];
            return json($return);
        }

        $tidsArray = array();
        foreach ($tempTidsArray as $key => $val) {
            if ($val) {
                $tidsArray[] = $val;
            }
        }

        if (empty($tidsArray)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tids]'];
            return json($return);
        }

        $resDataList = array();
        for ($i = 0; $i < count($tidsArray); $i++) {
            $w = array();
            $w['is_delete'] = 0;//未删除
            $w['tid'] = $tidsArray[$i];
            $w['type'] = 0;//0回复 1点赞

            $model = new \app\admin\model\NotesReply();
            $lists = $model->lists($w, $this->pagesize);
            $total = $lists['total'];
            $lists = $lists['data'];
            $lists = formateTimeForArr($lists, 'ctime');//获取发帖人信息
            $lists = changeUidToUserinfoForLists($lists, 'uid', 'touid');//获取发帖人信息
            $lists = getNotesFilesForLists($lists, 1, "sorts desc,id desc");//批量获取帖子列表中的附件数据
            $resDataList[$tidsArray[$i]] = array(
                'total' => $total,
                'lists' => $lists,
            );
        }


        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $resDataList;
        return json($return);
    }


    /**
     * 获取一个帖子的点赞用户列表接口
     */
    public function zanLists()
    {
        $auth = trim(input("request.auth"));//用户auth
        $tid = trim(input("request.tid"));//帖子ID
        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }

        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        if (empty($tid)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tid]'];
            return json($return);
        }


        $w = array();
        $w['is_delete'] = 0;//未删除
        $w['tid'] = $tid;
        $w['type'] = 1;//0回复 1点赞

        $model = new \app\admin\model\NotesReply();
        $lists = $model->lists($w, $this->pagesize);

        $total = $lists['total'];
        $lists = $lists['data'];
        $lists = formateTimeForArr($lists, 'ctime');//获取发帖人信息
        $lists = changeUidToUserinfoForLists($lists, 'uid');//获取发帖人信息
        $lists = getNotesFilesForLists($lists, 1, "sorts desc,id desc");//批量获取帖子列表中的附件数据


        $userList = array();
        foreach ($lists as $key => $val) {
            if ($val['UserInfo']) {
                $userList[] = $val['UserInfo'];
            }
        }
        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $userList;
        $return['total'] = $total;
        return json($return);
    }


    /**
     * 批量获取一推帖子的点赞用户列表接口 只取第一页
     */
    public function zanPlLists()
    {
        $auth = trim(input("request.auth"));//用户auth
        $tids = trim(input("request.tids"));//帖子ID  1,2,3
        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }

        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        if (empty($tids)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tids]'];
            return json($return);
        }

        $tempTidsArray = explode(",", $tids);
        if (empty($tempTidsArray)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tids]'];
            return json($return);
        }

        $tidsArray = array();
        foreach ($tempTidsArray as $key => $val) {
            if ($val) {
                $tidsArray[] = $val;
            }
        }

        if (empty($tidsArray)) {
            $return = ['err' => 1, 'msg' => '获取失败', 'devMsg' => '获取失败，参数错误[tids]'];
            return json($return);
        }

        $resDataList = array();
        for ($i = 0; $i < count($tidsArray); $i++) {
            $w = array();
            $w['is_delete'] = 0;//未删除
            $w['tid'] = $tidsArray[$i];
            $w['type'] = 1;//0回复 1点赞
            $model = new \app\admin\model\NotesReply();
            $lists = $model->lists($w, $this->pagesize);
            $total = $lists['total'];
            $lists = $lists['data'];
            $lists = formateTimeForArr($lists, 'ctime');//获取发帖人信息
            $lists = changeUidToUserinfoForLists($lists, 'uid');//获取发帖人信息
            $lists = getNotesFilesForLists($lists, 1, "sorts desc,id desc");//批量获取帖子列表中的附件数据
            $userList = array();
            foreach ($lists as $key => $val) {
                if ($val['UserInfo']) {
                    $userList[] = $val['UserInfo'];
                }
            }
            $resDataList[$tidsArray[$i]] = array(
                'total' => $total,
                'list' => $userList
            );
        }


        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $resDataList;
        return json($return);
    }

    /**
     * 给帖子点赞接口
     */
    public function zan()
    {
        $auth = trim(input("request.auth"));//用户auth
        $tid = trim(input("request.tid"));//帖子ID
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }

        if (empty($tid)) {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败，参数错误[tid]'];
            return json($return);
        }

        $model = new \app\admin\model\Notes();
        $info = $model->getID($tid);
        if (empty($info)) {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败，参数错误[tid]'];
            return json($return);
        }

        if ($info['stats']) {
            $return = ['err' => 1, 'msg' => '操作失败,帖子已经下架', 'devMsg' => '操作失败，帖子已经下架'];
            return json($return);
        }

        if ($info['is_delete']) {
            $return = ['err' => 1, 'msg' => '操作失败,帖子已经不存在', 'devMsg' => '操作失败，帖子已经不存在'];
            return json($return);
        }


        $flag = getTidIsZan($userInfo['id'], $tid);//0未点赞 1已经点赞
        if ($flag) {
            $return = ['err' => 1, 'msg' => '操作失败,您已经对该帖子点赞', 'devMsg' => '操作失败，您已经对该帖子点赞'];
            return json($return);
        }
        if (notesZan($userInfo['id'], $tid)) {
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }

    }

    /**
     * 发帖接口
     * @return \think\response\Json
     */
    public function pub()
    {
        $auth = trim(input("request.auth"));//用户auth
        $name = trim(input("request.name"));//贴名称
        $content = trim(input("request.content"));//帖子内容
        $ty = trim(input("request.ty"));//帖子类型 1话题 2梦话
        $img = trim(input("request.img"));//帖子类型是梦话的时候，梦话的背景图
        $json_images = trim(input("request.json_images"));//json字符串
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }

        if (empty($ty)) {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败，参数错误[ty]'];
            return json($return);
        }

        if (empty($content)) {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败，参数错误[content]'];
            return json($return);
        }

        if (empty($img)) {
            $img = "";
        }

        $model = new \app\admin\model\Notes();
        $nodeData = array(
            'name' => $name,
            'content' => $content,
            'name' => $name,
            'img' => $img,
            'ctime' => time(),
            'uid' => $userInfo['id'],
            'stats' => 0,//0上架 1下架
            'hot' => 0,//0普通，1推荐
            'is_delete' => 0,// 0否 1是
            'ty' => $ty
        );
        $insertId = $model->add($nodeData);
        if ($insertId) {
            $this->addNotesFiles($insertId, $json_images, 0);
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }


    /**
     * 回复接口
     * @return \think\response\Json
     */
    public function replay()
    {
        $auth = trim(input("request.auth"));//用户auth
        $content = trim(input("request.content"));//帖子内容
        $tid = trim(input("request.tid"));//帖子ID
        $touid = trim(input("request.touid"));//回复的哪个用户的回复
        $json_images = trim(input("request.json_images"));//json字符串
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }

        if (empty($tid)) {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败，参数错误[tid]'];
            return json($return);
        }

        if (empty($content)) {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败，参数错误[content]'];
            return json($return);
        }
        if (empty($touid)) {
            $touid = 0;
        }


        $model = new \app\admin\model\NotesReply();
        $nodeData = array(
            'tid' => $tid,
            'type' => 0,
            'content' => $content,
            'ctime' => time(),
            'uid' => $userInfo['id'],
            'touid' => $touid,
            'is_delete' => 0,// 0否 1是
        );
        $insertId = $model->add($nodeData);
        if ($insertId) {
            $this->addNotesFiles($insertId, $json_images, 1);
            //增加帖子回复数量
            incNoteReplyNum($tid);
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }


    private function addNotesFiles($tid, $json_images, $typeid = 0)
    {
        if (empty($tid)) {
            return false;
        }
        if (empty($json_images)) {
            return false;
        }
        $json_images = json_decode($json_images, true);
        if (empty($json_images)) {
            return false;
        }

        $insertData = array();
        foreach ($json_images as $key => $val) {
            $ty = 1;
            $suffix = getSuffixForFile($val['file']);
            if (in_array($suffix, ['jpg', 'jpeg', 'png'])) {
                $ty = 1;
            } else if (in_array($suffix, ['mp3', 'mp4', 'avi', 'wmv', 'flv'])) {
                $ty = 2;
            } else {
                $ty = 3;
            }

            $tempData = array(
                'tid' => $tid,
                'file' => $val['file'],
                'thumb' => $val['thumb'],
                'ctime' => time(),
                'ty' => $ty,
                'typeid' => $typeid,
            );
            $insertData[] = $tempData;
        }
        if (empty($insertData)) {
            return false;
        }
        $model = new \app\admin\model\NotesFiles();
        $model->addAll($insertData);
    }

    function defaultDreamBgLists()
    {
        $lists = config("DreamDefaultBackgroundImages");
        $return['err'] = 0;
        $return['msg'] = '操作成功';
        $return['data'] = $lists;
        return json($return);
    }


    /**
     * 统计当前用户 发帖动态数量  关注的人数  粉丝人数
     * @return \think\response\Json
     */
    public function statistics()
    {
        $auth = trim(input("request.auth"));//用户auth
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }
        $resData = array(
            'fans' => 0,
            'guanzhu' => 0,
            'dongtai' => 0,
        );
        $model = new \app\admin\model\UserFriend();
        //获取粉丝数量
        $sql = "select count(*) as num from t_user_friend where fuid = '{$userInfo['id']}'";
        $result = $model->querySelectSQL($sql);
        if ($result[0]['num']) {
            $resData['fans'] = $result[0]['num'];
        }
        //获取我关注的数量
        $sql = "select count(*) as num from t_user_friend where uid = '{$userInfo['id']}'";
        $result = $model->querySelectSQL($sql);
        if ($result[0]['num']) {
            $resData['guanzhu'] = $result[0]['num'];
        }
        //获取我发帖数
        $sql = "select count(*) as num from t_notes where uid = '{$userInfo['id']}' and is_delete=0";
        $result = $model->querySelectSQL($sql);
        if ($result[0]['num']) {
            $resData['dongtai'] = $result[0]['num'];
        }


        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $resData;
        return json($return);

    }


    /**
     * 统计当前用户 发帖动态数量  关注的人数  粉丝人数
     * @return \think\response\Json
     */
    public function del()
    {
        $auth = trim(input("request.auth"));//用户auth
        $tid = trim(input("request.tid"));//用户auth
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($tid)) {
            $return = ['err' => 1, 'msg' => '操作失败,参数错误', 'devMsg' => '操作失败，参数错误[tid]'];
            return json($return);
        }
        $model = new \app\admin\model\Notes();
        $info = $model->getID($tid);
        if (empty($info)) {
            $return = ['err' => 1, 'msg' => '操作失败，记录不存在', 'devMsg' => '操作失败，参数错误[tid]'];
            return json($return);
        }

        if ($info['is_delete']) {
            $return = ['err' => 1, 'msg' => '操作失败,帖子已经删除', 'devMsg' => '操作失败，帖子已经删除'];
            return json($return);
        }

        if ($info['uid'] != $userInfo['id']) {
            $return = ['err' => 1, 'msg' => '操作失败,您无权操作该记录', 'devMsg' => '操作失败，不是自己发的帖子'];
            return json($return);
        }

        $res = $model->updateData(array('is_delete' => 1), $tid);
        if ($res || $res == 0) {
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作成功';
            return json($return);
        }
    }


    public function getcls(){
        $lists = getNewWindProductClass();
        $return = ['err' => 0, 'msg' => '成功', 'data' => $lists];
        return json($return);
    }

}
